package com.eastday;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.JDOMException;

import com.eastday.biz.ParseHtmlBiz;
import com.eastday.util.BeanFactory;
import com.eastday.util.ExceptionHandler;
import com.eastday.util.ParseConfigFactory;

/**
 * 
 * @author dingxs
 *
 */
public class HtmlProcess implements Runnable {

	private ExceptionHandler exceptionHandler;
	private int interval;//时间间隔
	
	
	public int getInterval() {
		return interval;
	}


	public void setInterval(int interval) {
		this.interval = interval;
	}


	public HtmlProcess(){
		try{
			ParseConfigFactory.constructSysConfig();
			exceptionHandler = new ExceptionHandler();
			interval = ParseConfigFactory.sysConfigModel.getInterval();
		}catch(JDOMException e){
			exceptionHandler.writeToLog(e.getMessage());
		}catch(IOException e){
			exceptionHandler.writeToLog(e.getMessage());
		}
	}
	
	private void htmlprocess(){
		ParseHtmlBiz parseHtmlBiz = (ParseHtmlBiz)BeanFactory.getBean("ParseHtmlBiz");
		try {
			ParseConfigFactory.constructUrlConfig();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			exceptionHandler.writeToLog(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			exceptionHandler.writeToLog(e.getMessage());
		}
		Map<String,String[]> urlMap = ParseConfigFactory.urlConfigModel.getUrlConfigMap();
		Set urlSet = urlMap.keySet();
		Iterator iterator = urlSet.iterator();
		while(iterator.hasNext())
		{
			String url = iterator.next().toString();
			List<String> pagelinkList = parseHtmlBiz.parseHtmlPageLink(url);
			parseHtmlBiz.parseHtmlToDb(pagelinkList, url);
			exceptionHandler.displayOnConsole(url+" parse has finished");
		}
		exceptionHandler.displayOnConsole("parse wait...");
		
	}
	

	

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			try {
				this.htmlprocess();
				Thread.sleep(interval*60*1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				exceptionHandler.writeToLog(e.getMessage());
			}
		}
	}
	
}
